package com.example.xunai.service.conversation.impl;

import com.example.xunai.dto.response.conversation.MessageResponse;
import com.example.xunai.entity.ConversationMessage;
import com.example.xunai.repository.ConversationMessageRepository;
import com.example.xunai.service.conversation.ConversationMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ConversationMessageServiceImpl implements ConversationMessageService {

    private final ConversationMessageRepository conversationMessageRepository;

    @Override
    public ConversationMessage saveMessage(ConversationMessage message) {
        return conversationMessageRepository.save(message);
    }

    @Override
    public List<ConversationMessage> saveAll(List<ConversationMessage> messages) {
        return conversationMessageRepository.saveAll(messages);
    }

    @Override
    public List<ConversationMessage> getMessagesByConversationId(Long conversationId) {
        return conversationMessageRepository.findByConversationIdOrderByTurnAsc(conversationId);
    }

    @Override
    public List<MessageResponse> getMessageResponsesByConversationId(Long conversationId) {
        List<ConversationMessage> messages = getMessagesByConversationId(conversationId);
        return messages.stream()
                .map(MessageResponse::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    public Integer getLastTurnByConversationId(Long conversationId) {
        return conversationMessageRepository.findLastTurnByConversationId(conversationId);
    }

    @Override
    public ConversationMessage getMessageById(Long id) {
        return conversationMessageRepository.findById(id).orElse(null);
    }

    @Override
    public MessageResponse getMessageResponseById(Long id) {
        ConversationMessage message = getMessageById(id);
        return message != null ? MessageResponse.fromEntity(message) : null;
    }

    @Override
    public void deleteMessage(Long id) {
        conversationMessageRepository.deleteById(id);
    }

    @Override
    public void deleteMessagesByConversationId(Long conversationId) {
        conversationMessageRepository.deleteByConversationId(conversationId);
    }
}